import traceback

from flask import Blueprint, request

from shop.util.mylogger import Blogger
from shop.util.wx_util import WXHandler

wx1 = Blueprint('wx1', __name__)


def get_request_params(*args):
    '''
    获取参数的方法
    :param args:
    :return:
    '''
    params = request.values
    param_value_list = []
    for one_args in args:
        param_value_list.append(params.get(one_args))
    return tuple(param_value_list)


def create_wx1_menu():
    '''
    创建微信菜单
    :return:
    '''
    wxh = WXHandler()
    try:
        wxh.create_menu()
    except Exception as e:
        exception_detail = traceback.format_exc()
        Blogger.error(exception_detail)
        return str(e)


@wx1.route("/", methods=['GET', 'POST'])
def index():
    try:
        if request.method == "GET":
            # get请求
            signature, timestamp, nonce, echostr = get_request_params("signature", "timestamp", "nonce", "echostr")
            Blogger.info(signature, timestamp, nonce, echostr)
            wxh = WXHandler()
            check_res = wxh.check_wx_reqeust(signature, timestamp, nonce)
            if check_res:
                return echostr
            else:
                return "error"
        elif request.method == "POST":
            # post请求
            resp_data = request.data
            wxh = WXHandler()
            resp = wxh.analysis_wx_data(resp_data)
            return resp
    except Exception as e:
        exception_detail = traceback.format_exc()
        Blogger.error(exception_detail)
        return ""
